const MD5 = require("md5");
const base64 = require("js-base64");
base64.Base64.extendString();
const axios = require("axios").default;
const qs = require("querystring");
const rannum = require("random-number");
const util = require("util");

function getSig(timestamp) {
  return MD5(`4762000` + "" + timestamp).toUpperCase();
}

function getTimeString() {
  let d = new Date;
  let month = d.getMonth() + 1;
  if (month < 10) {
    month = '0' + month;
  }
  let dayOfMonth = d.getDate();
  if (dayOfMonth < 10) {
    dayOfMonth = '0' + dayOfMonth;
  }
  let hour = d.getHours();
  if (hour < 10) hour = '0' + hour;
  let minute = d.getMinutes();
  if (minute < 10) minute = '0' + minute;
  let second = d.getSeconds();
  if (second < 10) second = '0' + second;
  /** @todo*/
  return `${d.getFullYear()}${month}${dayOfMonth}${hour}${
    minute
    }${second}`
}


/**
 * 
 * @param {String} ext_name 
 * @returns {Promise<{ok:Boolean,msg:String,token:String,remote_filename:String}>}
 */
function getUploadToken(ext_name = "bin") {
  return new Promise(async resolve => {
    let timestamp = getTimeString();
    axios.post(`http://pianke.me/version5.0/additional/getQNUploadToken.php?sig=${getSig(timestamp)}`,
      qs.stringify({ filetype: ext_name }),
      {
        headers: {
          "User-Agent": `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/5${rannum({ min: 25, max: 37 })}.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36`,
          Referer: "http://pianke.me/editor/",
          "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
          "X-Requested-With": "XMLHttpRequest",
          Authorization: `4762000:${timestamp}`.toBase64(true) //这里前面的userid居然可以假装别人的哈哈哈哈
        },
        validateStatus: s => s == 200
      }
    ).then(getit => {
      let token = getit.data['data']['token'];
      let remote_filename = getit.data['data']['filename'];
      resolve({
        ok: true,
        msg: "ok",
        token: token,
        remote_filename: remote_filename
      })
    }).catch(axerr => {
      resolve({
        ok: false,
        msg: `${
          axerr.response ? `HTTP ${axerr.response.status + axerr.response.statusText};${util.inspect(axerr.response.data)}` : axerr.message
          }`,
        token: '',
        remote_filename: ''
      })
    })
  })

}

if (!module.parent) {
  getUploadToken()
}


module.exports = {
  getUploadToken:getUploadToken
}